package cn.xlmdz.subsoilerinfoquery.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.codbking.widget.DatePickDialog;
import com.codbking.widget.OnSureLisener;
import com.codbking.widget.bean.DateType;
import com.kevin.delegationadapter.DelegationAdapter;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import cn.xlmdz.subsoilerinfoquery.adapter.QuerySingleListAdapter;
import cn.xlmdz.subsoilerinfoquery.app.Constants;
import cn.xlmdz.subsoilerinfoquery.app.MyApplication;
import cn.xlmdz.subsoilerinfoquery.bean.SubsoilDataListBean;
import cn.xlmdz.subsoilerinfoquery.databinding.ActivityMainBinding;
import cn.xlmdz.subsoilerinfoquery.databinding.ActivityQuerySingleBinding;
import cn.xlmdz.subsoilerinfoquery.http.ApiEngine;
import cn.xlmdz.subsoilerinfoquery.http.ApiServices;
import cn.xlmdz.subsoilerinfoquery.http.NetworkInterceptor;
import cn.xlmdz.subsoilerinfoquery.utils.ToastUtil;
import cn.xlmdz.subsoilerinfoquery.view.LoadingDialog;
import cn.xlmdz.subsoilerinfoquery.view.VerticalSpacingItemDecoration;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import okhttp3.Cache;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;
import okio.Buffer;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class QuerySingleActivity extends AppCompatActivity {

    private ActivityQuerySingleBinding viewBinding;
    private LoadingDialog loadingDialog;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    private String terminalId = null;

    /*** 委托适配器 */
    private DelegationAdapter mDelegationAdapter;
    private QuerySingleListAdapter listAdapterDelegate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewBinding = ActivityQuerySingleBinding.inflate(getLayoutInflater());
        setContentView(viewBinding.getRoot());

        Intent intent = getIntent();
        terminalId = intent.getStringExtra("terminalId");

        initDate();

        initViews();
        initToolbar();
        initRecyclerView();

        queryData();
    }

    private void initToolbar() {
        viewBinding.tvTitleTerminalId.setText(terminalId);
        viewBinding.toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initRecyclerView() {
        //layoutManager
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        viewBinding.recycleViewShow.setLayoutManager(layoutManager);

        //设置item间隔
        VerticalSpacingItemDecoration itemDecoration = new VerticalSpacingItemDecoration(20);
        viewBinding.recycleViewShow.addItemDecoration(itemDecoration);

        //设置回收复用池大小--如果一屏内相同类型的 View 个数比较多，需要设置一个合适的大小，防止来回滚动时重新创建 View
        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        viewBinding.recycleViewShow.setRecycledViewPool(viewPool);
        viewPool.setMaxRecycledViews(0, 15);

        // listView内容适配器
        listAdapterDelegate = new QuerySingleListAdapter(this, 0);
        mDelegationAdapter = new DelegationAdapter();
        mDelegationAdapter.addDelegate(listAdapterDelegate);
        viewBinding.recycleViewShow.setAdapter(mDelegationAdapter);
    }

    private void initViews() {
        viewBinding.tvStartTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickDialog(new OnSureLisener() {
                    @Override
                    public void onSure(Date date) {
                        viewBinding.tvStartTime.setText(sdf.format(date) + " 00:00:00");
                    }
                });
            }
        });
        viewBinding.tvEndTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickDialog(new OnSureLisener() {
                    @Override
                    public void onSure(Date date) {
                        viewBinding.tvEndTime.setText(sdf.format(date) + " 00:00:00");
                    }
                });
            }
        });
        viewBinding.ibSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                queryData();
            }
        });
    }

    private void queryData() {
        if (TextUtils.isEmpty(terminalId)) {
            ToastUtil.showTextToast("终端号错误");
            return;
        }
        showLoading();
        ApiServices services = ApiEngine.getInstance().getApiService();

        Map<String, String> params = new HashMap<>();
        String begin = viewBinding.tvStartTime.getText().toString();
        String end = viewBinding.tvEndTime.getText().toString();
        String terminal_id = terminalId;
        params.put("begin", begin);
        params.put("end", end);
        params.put("terminal_id", terminal_id);

        Observable<SubsoilDataListBean> observable = services.getSubsoilData(params);
        observable.subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<SubsoilDataListBean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull SubsoilDataListBean dataList) {
                        if (dataList == null || dataList.getData() == null || dataList.getData().getInfo() == null) {
                            ToastUtil.showTextToast("未查找到改车辆信息");
                            showNoDataView(true);
                            viewBinding.tvCarNumber.setText("");
                            viewBinding.tvSumArea.setText("0.0");
                        } else {
//                            if (dataList.getData().getInfo().getAuth().equals("auto")) {
//                                listAdapterDelegate.setDataType(1);
//                                viewBinding.tvSumArea.setText(dataList.getData().getInfo().getAuto_sum_area());
//                            } else {
//                                listAdapterDelegate.setDataType(2);
//                                viewBinding.tvSumArea.setText(dataList.getData().getInfo().getSum_area().toString());
//                            }
                            if (dataList.getData().getInfo().getSum_area() != null){
                                viewBinding.tvSumArea.setText(dataList.getData().getInfo().getSum_area().toString());
                            }
                            viewBinding.tvCarNumber.setText(dataList.getData().getInfo().getNumber());
                            if (dataList.getData().getWork().size() > 0) {
                                mDelegationAdapter.setDataItems(dataList.getData().getWork());
                                showNoDataView(false);
                            } else {
                                showNoDataView(true);
                            }
                            listAdapterDelegate.setInfo(dataList.getData().getInfo());
                        }
                        hideLoading();
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        hideLoading();
                    }

                    @Override
                    public void onComplete() {
                        hideLoading();
                    }
                });
    }

    private void showNoDataView(boolean isNoData) {
        if (isNoData) {
            viewBinding.recycleViewShow.setVisibility(View.GONE);
            viewBinding.llNoData.setVisibility(View.VISIBLE);
        } else {
            viewBinding.recycleViewShow.setVisibility(View.VISIBLE);
            viewBinding.llNoData.setVisibility(View.GONE);
        }
    }

    private void initDate() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_YEAR, 1);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.clear(Calendar.MINUTE);
        cal.clear(Calendar.MILLISECOND);
        viewBinding.tvStartTime.setText(sdf.format(cal.getTime()));

        cal.add(Calendar.YEAR, 1);
        viewBinding.tvEndTime.setText(sdf.format(cal.getTime()));
    }

    private void showDatePickDialog(OnSureLisener lisener) {
        DatePickDialog dialog = new DatePickDialog(this);
        //设置上下年份限制
        dialog.setYearLimt(2);
        //设置标题
        dialog.setTitle("选择时间");
        //设置类型
//        dialog.setType(DateType.TYPE_YMDHM);
        dialog.setType(DateType.TYPE_YMD);
        //设置消息体的显示格式，日期格式
        dialog.setMessageFormat("yyyy-MM-dd");
        //设置选择回调
        dialog.setOnChangeLisener(null);
        //设置点击确定按钮回调
        dialog.setOnSureLisener(lisener);
        dialog.show();
    }

    public void showLoading() {
        if (loadingDialog == null)
            loadingDialog = new LoadingDialog(this, "加载中…");
        if (!loadingDialog.isShowingNew())
            loadingDialog.show();
    }

    public void hideLoading() {
        if (loadingDialog != null && loadingDialog.isShowingNew())
            loadingDialog.close();
    }
}